<template>
  <div class="cesium-wrap" :class="editorStore.mouseClass">
    <div id="cesiumContainer"></div>
  </div>
  <!-- 加载进度条 -->
  <Loading v-if="loading" :loading-complete="initialized" @close="loading = false" />
  <template v-if="initialized">
    <slot />
  </template>
</template>

<script setup lang="ts">
import AppCore from '@/service/interaction/core/App';
import { useEditorStore } from '@/store/editor';
import Loading from './components/loading/index.vue';
import { defaultMapObject } from './config';
import { Mode } from './types';

interface IProps {
  mode: Mode;
}

defineOptions({
  name: 'Cesium',
});

const props = withDefaults(defineProps<IProps>(), {
  mode: 'edit',
});

provide('mode', props.mode);

const editorStore = useEditorStore();
const loading = ref<boolean>(true);
const initialized = ref<boolean>(false);

onMounted(() => {
  init();
});

onBeforeUnmount(() => {
  // TODO: 销毁 cimup 实例
});

const init = async () => {
  const { CIMUP } = window;
  const cimInstance = CIMUP.CimEngine.instance;
  window.cimInstance = cimInstance;

  // 解析保存的全局特效
  try {
    const configJson = editorStore.sceneDetail.configJson
      ? JSON.parse(editorStore.sceneDetail.configJson)
      : null;
    if (configJson) {
      const { view, materialMap, light, postProcess } = configJson?.stage?.mapObject;
      Object.assign(defaultMapObject, { view, materialMap, light, postProcess });
    }
  } catch (error) {
    console.log(error);
  }

  const cimInitConfig: any = {
    config: {
      gisContainer: 'cesiumContainer',
      map: '谷歌',
      mapObject: defaultMapObject,
    },
  };

  cimInstance.init(cimInitConfig);
  cimInstance.eventApi.addEventListener('scene_tile_loaded', tileLoadComplete);
};

function tileLoadComplete() {
  console.log('--地图加载完成--');
  initialized.value = true;
  if (props.mode === 'preview') {
    const configJson = editorStore.sceneDetail.configJson
      ? JSON.parse(editorStore.sceneDetail.configJson)
      : null;
    if (configJson) {
      window.appCore = new AppCore(configJson);
    }
  }
}

watch(
  () => initialized.value,
  () => {
    const { cimInstance } = window;
    if (initialized.value) {
      cimInstance.eventApi.removeEventListener('scene_tile_loaded', tileLoadComplete);
    }
  }
);
</script>

<style lang="less" scoped>
.cesium-wrap,
#cesiumContainer {
  position: absolute;
  width: 100%;
  height: 100%;

  &.select {
    cursor: url('~@/assets/png/ic_吸管.png') 0 0, auto;
  }

  &.selectable {
    cursor: url('~@/assets/png/ic_可选择状态.png') 0 0, auto;
  }

  &.unselectable {
    cursor: url('~@/assets/png/ic_不可选.png') 0 0, auto;
  }
}
.cesium-wrap {
  position: relative;
  overflow: hidden;
}
</style>
